/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.gerenciadorfinanceiro.face;

import java.util.Map;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.ValidatorException;
import org.gerenciadorfinanceiro.ejb.entity.User;
import org.gerenciadorfinanceiro.ejb.session.interfaces.UsuarioSessionLocal;
import org.gerenciadorfinanceiro.face.form.LoginFormBean;

/**
 *
 * @author eduardo
 */

public class LoginFace {

    @EJB
    private UsuarioSessionLocal userBean;

    private LoginFormBean formBean = new LoginFormBean();

    /** Creates a new instance of LoginFace */
    public LoginFace() {
    }

    /**
     * @return the formBean
     */
    public LoginFormBean getFormBean() {
        return formBean;
    }

    public String doLogin() {
        String username = this.getFormBean().getLogin();
        
        if (username != null) {
            User us = userBean.getUsuario(username);
            System.out.println("username: "+username);
            System.out.println("Usuario: "+us);
            FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("usuarioLogado", us);
        }

        return "gotoMain";
    }

    public void validateLoginAndPassword(FacesContext arg0, UIComponent arg1, Object arg2) {
        String username = getFormBean().getLoginUI().getLocalValue().toString();
        String password = arg2.toString();

        boolean valid = userBean.isUserAndPasswordValid(username, password);

        if (! valid) {
            FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_FATAL, "Usuario ou senha invalido !", "Usuario ou senha invalido !");
            throw new ValidatorException(msg);
        }
    }

}
